package com.huangmingfu;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 黄名富
 * @Description: 自定义URIBuilder
 */
public class CustomURIBuilder {

    public static void main(String[] args) throws URISyntaxException {
        CustomURIBuilder customURIBuilder = new CustomURIBuilder();
        customURIBuilder.setHost("localhost").setPort("8080").setEncodedPath("/userinfo");
        customURIBuilder.appendQueryParam("username","hmf");
        customURIBuilder.appendQueryParam("status","1");
        customURIBuilder.appendQueryParam("createDate","2024/04/20");
        URI uri = customURIBuilder.build();
        System.out.println(uri);
    }

    private String scheme;

    private String host;

    private String port;

    private String encodedPath;

    private List<NameValuePair> queryParams;

    public CustomURIBuilder setScheme(String scheme) {
        this.scheme = scheme;
        return this;
    }

    public CustomURIBuilder setHost(String host) {
        this.host = host;
        return this;
    }

    public CustomURIBuilder setPort(String port) {
        this.port = port;
        return this;
    }

    public CustomURIBuilder setEncodedPath(String encodedPath) {
        this.encodedPath = encodedPath;
        return this;
    }

    public CustomURIBuilder appendQueryParam(String name,String value) {
        if (queryParams == null) queryParams = new ArrayList<>();
        queryParams.add(new NameValuePair(name,value));
        return this;
    }

    public URI build() throws URISyntaxException {
        return new URI(buildStr());
    }

    public String buildStr() {
        StringBuilder sb = new StringBuilder();
        if (this.scheme != null) sb.append(this.scheme).append("://");
        if (this.host == null) throw new RuntimeException("host不能为空");
        sb.append(this.host);
        if (this.port != null) sb.append(":").append(this.port);
        if (this.encodedPath != null) sb.append(this.encodedPath);
        if (this.queryParams != null) {
            for (int i = 0; i < this.queryParams.size(); i++) {
                sb.append(i == 0 ? "?" : "&").append(this.queryParams.get(i));
            }
        }
        return sb.toString();
    }

    private static class NameValuePair {
        String name;
        String value;

        public NameValuePair(String name, String value) {
            this.name = name;
            this.value = value;
        }

        @Override
        public String toString() {
            if (this.value == null) return name;
            return name + "=" + value;
        }
    }

}
